#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    long long countSubarrays(vector<int>& nums, int k) {
        int len = nums.size();
        long long ans = 0;
        int cnt = 0;
        int maxn = 0;
        for (int i = 0; i < len; i++) {
            maxn = max(maxn, nums[i]);
        }

        for (int i = 0, j = 0; i < len; i++) {
            if (nums[i] == maxn) {
                cnt++;
            }

            while (j <= i && cnt >= k) {
                if (nums[j++] == maxn) {
                    cnt--;
                }
            }
            //cout<<j<<" "<<i<<endl;
            ans += (j);

        }
        return ans;
    }
};